// Learn cc.Class:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/class.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/class.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/life-cycle-callbacks.html
var Shares = require('gameshare');
var FileTool = require('../utils/file_tools')

var SceneTypes = Shares.SceneTypes;
var GameEvent = Shares.GameEvent;
var GameObject = Shares.GameObject;
var GameConst = Shares.GameConst;

cc.Class({
    extends: cc.Component,

    properties: {
        trianglePrefab: cc.Prefab,
        trapPrefab: cc.Prefab,
        playerPrefab: cc.Prefab,
        blockPrefab: cc.Prefab,
        starPrefab: cc.Prefab,
        mapnode: cc.Node,
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad() {
        this.height = GameConst.height;
        this.width = GameConst.width;
        this.size = GameConst.size;
        this.map = new Array(this.width * this.height);
        this.isDelMode = false;
        cc.zsb.map = this;
        cc.systemEvent.on(GameEvent.EnterEdit, this.onEnterEdit, this);
        cc.systemEvent.on(GameEvent.GetStar, this.onGetStar, this);
        cc.systemEvent.on(GameEvent.RemoveBlock, this.onRemoveBlock, this);
        cc.systemEvent.on(GameEvent.LoadMap, this.onLoadMap, this);
    },

    onGetStar(event) {
        var isGameOver = true;
        for (var i = 0; i < this.map.length; i++) {
            if (this.map[i] != null && this.map[i].view == event) {
                this.map[i].view.removeFromParent();
                this.map[i] = null;
            }
            else if (this.map[i] != null && this.map[i].data.objectType == GameObject.Star && this.map[i].view != event) {
                console.log(i);
                isGameOver = false;
            }
        }

        if (isGameOver) {
            cc.systemEvent.emit(GameEvent.GameWin);
        }
    },

    onRemoveBlock(event) {

        for (var i = 0; i < this.map.length; i++) {
            if (this.map[i] != null && this.map[i].view == event) {
                this.map[i].view.removeFromParent();
                this.map[i] = null;
            }

        }
    },

    onEnterEdit() {
        var self = this;
        this.resetMap();

        var delfunc = function (idx) {
            if (self.map[idx]) {
                cc.zsb.selectElement = self.map[idx];
                cc.zsb.selectIdx = idx;
                if (cc.zsb.selectElement) {
                    var view = cc.zsb.selectElement.view;
                    view.removeFromParent();
                    self.map[cc.zsb.selectIdx] = null;
                    cc.zsb.selectElement = null;
                }
            }
        }

        var startTouchFunc = function (idx, localtion) {
            if (self.map[idx] == null) {
                self.doAddElement(idx, localtion);
            }
            else {
                cc.zsb.selectElement = self.map[idx];
                cc.zsb.selectIdx = idx;
                //data.detail
                cc.systemEvent.emit(GameEvent.ElementSelect, self.map[idx]);
            }
        }

        var self = this;
        this.node.on(cc.Node.EventType.TOUCH_START, function (event) {
            var localtion = this.node.convertToNodeSpaceAR(event.getLocation());
            var idx = this.getIdxFromPos(localtion);
            if (this.isDelMode) {
                delfunc();
            }
            else {
                startTouchFunc(idx, localtion);
            }

        }, this);

        this.node.on(cc.Node.EventType.TOUCH_MOVE, function (event) {
            var localtion = this.node.convertToNodeSpaceAR(event.getLocation());
            var idx = this.getIdxFromPos(localtion);
            if (this.isDelMode) {
                delfunc(idx);
            }
            else {
                if (this.map[idx] == null) {
                    this.doAddElement(idx, localtion);
                }
            }

        }, this);

        cc.loader.loadRes("default", function (err, res) {
            if (err) {
                cc.log(err);
            } else {
                self.setData(res);
            }
        });
    },

    onLoadMap(event) {
        var self = this;
        console.log(event);
        this.resetMap();
        cc.loader.loadRes(event, function (err, res) {
            console.log(event);
            console.log(res);
            if (err) {
                cc.log(err);
            } else {
                self.setData(res.json);
            }
        });
    },

    onBtnSave() {
        var savedata = this.toData();
        console.log(savedata);
        //cc.sys.localStorage.setItem('testmap', JSON.stringify(savedata));
        FileTool.saveForBrowser(JSON.stringify(savedata), new Date().getTime());
    },

    onBtnChange() {
        if (cc.zsb.selectElement) {
            var data = cc.zsb.selectElement.data;
            if (data.objectType == GameObject.RotateTri || data.objectType == GameObject.StaticTri) {
                cc.zsb.selectElement.view.getComponent('triangle').rotateRight();
                cc.zsb.selectElement.data = cc.zsb.selectElement.view.getComponent('triangle').toData();
            }
            else if (data.objectType == GameObject.SwitchTri) {
                cc.zsb.selectElement.view.getComponent('triangle').switchShow();
                cc.zsb.selectElement.data = cc.zsb.selectElement.view.getComponent('triangle').toData();
            }
            else if (data.objectType == GameObject.Player) {
                cc.zsb.selectElement.view.getComponent('player').rotateRight();
                cc.zsb.selectElement.data = cc.zsb.selectElement.view.getComponent('player').toData();
            }
        }
    },

    onBtnDel() {
        this.isDelMode = !this.isDelMode;
    },

    start() {
        var self = this;
        cc.systemEvent.on(GameEvent.PlayerRetry, function (event) {
            self.resetMap();
            self.onLoadMap('map_' + cc.zsb.mapIdx);
        });
    },

    doAddElement(idx, localtion) {
        if (cc.zsb.sceneType == SceneTypes.SceneEdit && cc.zsb.selectNode != null) {
            var script = cc.zsb.selectNode.getComponent('editnode');
            var instacne = cc.instantiate(script.ins);
            instacne.parent = this.node;
            instacne.position = localtion.add(cc.v2(this.size / 2, this.size / 2));
            instacne.mapidx = idx;
            this.map[idx] = {};
            this.map[idx].view = instacne;

            if (script.nodeType == GameObject.StaticTri || script.nodeType == GameObject.RotateTri || script.nodeType == GameObject.SwitchTri) {
                instacne.getComponent('triangle').objectType = script.nodeType;
                this.map[idx].data = instacne.getComponent('triangle').toData();
                instacne.getComponent('triangle').refresh();
            }
            else if (script.nodeType == GameObject.StaitcBlock) {
                this.map[idx].data = instacne.getComponent('block').toData();
                cc.systemEvent.emit(GameEvent.AddBlock);
            }
            else if (script.nodeType == GameObject.OneceBlock) {
                instacne.getComponent('block').objectType = script.nodeType;
                this.map[idx].data = instacne.getComponent('block').toData();
                cc.systemEvent.emit(GameEvent.AddBlock);
            }
            else if (script.nodeType == GameObject.StaticTrap) {
                this.map[idx].data = instacne.getComponent('trap').toData();
            }
            else if (script.nodeType == GameObject.Player) {
                this.map[idx].data = instacne.getComponent('player').toData();
                instacne.getComponent('player').isPause = true;
            }
            else if (script.nodeType == GameObject.Star) {
                this.map[idx].data = instacne.getComponent('star').toData();
            }
            instacne.zIndex = 999 - idx;
            //var savedata = this.toData();
            //cc.sys.localStorage.setItem('testmap', JSON.stringify(savedata));
        }
    },

    toData() {
        var cloneMap = new Array(this.width * this.height);
        for (var i = 0; i < this.map.length; i++) {
            if (this.map[i] != null) {
                var mapdata = {};
                mapdata.data = this.map[i].data;
                cloneMap[i] = mapdata;
            }

        }

        return cloneMap;
    },

    resetMap() {
        cc.zsb.selectElement = null;
        this.node.removeAllChildren();
        this.map = new Array(this.width * this.height);
    },

    setData(mapdata) {
        if (cc.zsb.sceneType == SceneTypes.SceneEdit) {
            this.drawMap();
        }
        for (var i = 0; i < mapdata.length; i++) {
            if (mapdata[i]) {
                this.map[i] = mapdata[i];
                var info = mapdata[i].data;
                var type = mapdata[i].data.objectType;
                var instacne
                if (type == GameObject.StaticTri || type == GameObject.RotateTri || type == GameObject.SwitchTri) {
                    instacne = cc.instantiate(this.trianglePrefab);
                    instacne.parent = this.node;
                    instacne.getComponent('triangle').setData(info);
                    this.map[i].view = instacne;
                }
                else if (type == GameObject.StaitcBlock || type == GameObject.OneceBlock) {
                    instacne = cc.instantiate(this.blockPrefab);
                    instacne.parent = this.node;
                    instacne.getComponent('block').setData(info);
                    this.map[i].view = instacne;
                }
                else if (type == GameObject.StaticTrap) {
                    instacne = cc.instantiate(this.trapPrefab);
                    instacne.parent = this.node;
                    instacne.getComponent('trap').setData(info);
                    this.map[i].view = instacne;
                }
                else if (type == GameObject.Player) {
                    instacne = cc.instantiate(this.playerPrefab);
                    instacne.parent = this.node;
                    instacne.getComponent('player').setData(info);
                    if (cc.zsb.sceneType == SceneTypes.SceneTitle || cc.zsb.sceneType == SceneTypes.SceneGame) {
                        instacne.getComponent('player').isPause = false;
                    }
                    else {
                        instacne.getComponent('player').isPause = true;
                    }
                    this.map[i].view = instacne;
                }
                else if (type == GameObject.Star) {
                    instacne = cc.instantiate(this.starPrefab);
                    instacne.parent = this.node;
                    instacne.getComponent('star').setData(info);
                    this.map[i].view = instacne;
                }
                this.height = GameConst.height;
                this.width = GameConst.width;
                instacne.zIndex = 999 - i;
                instacne.position = cc.p(
                    (Math.floor(i % this.width) + 0.5) * this.size,
                    (Math.floor(i / this.width) + 0.5) * this.size)
            }
        }
    },

    getIdxFromPos(localtion) {
        return Math.floor(localtion.y / this.size) * this.width + Math.floor(localtion.x / this.size);
    },

    drawMap() {
        var ctx = this.mapnode.getComponent(cc.Graphics);
        console.log(ctx);
        var right = this.width * this.size;
        var top = this.height * this.size;

        for (var i = 0; i < this.height; i++) {
            ctx.moveTo(0, this.size * i);
            ctx.lineTo(right, this.size * i);
        }

        for (var i = 0; i < this.width; i++) {
            ctx.moveTo(this.size * i, 0);
            ctx.lineTo(this.size * i, top);
        }

        ctx.stroke();
    },

    update(dt) {

    },
});
